package cn.scxy.bookcity.service.impl;

import cn.scxy.bookcity.ex.ServiceException;
import cn.scxy.bookcity.mapper.AdminLoginMapper;
import cn.scxy.bookcity.pojo.dto.AdminLoginDTO;
import cn.scxy.bookcity.service.IAdminLoginService;
import cn.scxy.bookcity.web.ServiceCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Service
@Slf4j
public class AdminLoginService implements IAdminLoginService {
    @Autowired
    AdminLoginMapper adminLoginMapper;

    @Override
    public AdminLoginDTO adminlogin(AdminLoginDTO adminLoginDTO, HttpServletResponse response, HttpSession session) {
        session.setMaxInactiveInterval(60*60*60);
        AdminLoginDTO u = adminLoginMapper.selectByUsername(adminLoginDTO.getUsername());
        log.debug("admin{}",u);
        if(u!=null){
            if (u.getPassword().equals(adminLoginDTO.getPassword())){
                if (adminLoginDTO.isC()){
                    Cookie c3 = new Cookie("username",adminLoginDTO.getUsername());
                    Cookie c4 = new Cookie("password",adminLoginDTO.getPassword());
                    c3.setMaxAge(60*5);
                    c4.setMaxAge(60*5);
                    response.addCookie(c3);
                    response.addCookie(c4);
                }
                //把当前登录的用户对象保存到Session里面
                session.setAttribute("admin",u);
                System.out.println("-------------------"+session.getAttribute("admin"));
                AdminLoginDTO admin =(AdminLoginDTO) session.getAttribute("admin");
                return admin;
            }
            throw new ServiceException(ServiceCode.ERR_SELECT,"密码错误");
        }
        throw new ServiceException(ServiceCode.ERR_SELECT,"用户名不存在");
    }

}
